import {defineStore} from "pinia";

export const useSysUserStore = defineStore("user", {
    state: () => ({
        tokenInfo: () => {
            const tokenInfo = sessionStorage.getItem("__token_info__")
            if (tokenInfo) {
                return JSON.parse(tokenInfo)
            }
            return undefined
        },
        expire: sessionStorage.getItem("__expire__") || 0,
        userInfo: undefined

    }),
    getters: {
        isLogin: (state) => {
            if (state.tokenInfo) {
                return state.expire > new Date().valueOf()
            }
            return false
        },
        hasUserInfo: (state) => state.userInfo !== undefined,
        tokenName: (state) => state.tokenInfo?.tokenName,
        tokenValue: (state) => state.tokenInfo?.tokenValue,
        loginId: (state) => state.tokenInfo?.loginId,
    },
    actions: {
        async login(tokenInfo) {
            const expire = ((tokenInfo.tokenTimeout || 0) * 1000) + new Date().valueOf()
            sessionStorage.setItem("__expire__", expire)
            sessionStorage.setItem("__token_info__", JSON.stringify(tokenInfo))
            this.expire = expire
            this.tokenInfo = tokenInfo
        },
        async logout() {
            sessionStorage.clear()
            this.tokenInfo = undefined
            this.expire = 0
        },
        async initUserInfo(userInfo) {
            this.userInfo = userInfo
        }
    }
})
